package com.wdt.data.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.util.StringUtils;

import java.io.*;

/**
 * json工具类
 */
public class JsonUtil {

    /**
     * 如果JSON字符串为Null或"null"字符串,返回Null.
     * 如果JSON字符串为"[]",返回空集合.
     * 如需读取集合如List/Map,使用如下语句:
     * List list=JsonUtil.fromJson(jsonString,List.class)
     */
    public static <T> T fromJson(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        return JSON.parseObject(jsonString, clazz);
    }


    /**
     * 如果JSON字符串为Null或"null"字符串,返回Null.
     * 如果JSON字符串为"[]",返回空集合.
     *
     * 如需读取集合如List/Map,且不是List<String>这种简单类型时使用如下语句:
     * List<MyBean> beanList = binder.getMapper().readValue(listString, new TypeReference<List<MyBean>>() {});
     */
    public static <T> T readJsonFromFile(File file,Class<T> cls) throws IOException {
        StringBuilder strBuilder = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line = null;
        while ((line = br.readLine()) != null) {
            strBuilder.append(line);
        }
        br.close();
        return JSON.parseObject(strBuilder.toString(), cls);
    }

    public static <T> T readJsonFromFile(Class<T> cls, String filename) throws IOException {
        return readJsonFromFile( new File(filename),cls);
    }


    /**
     * 如果对象为Null,返回"null".
     * 如果集合为空集合,返回"[]".
     */
    public static String toJson(Object object) {
        return JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 验证json格式是否正确
     * @return boolean - 验证结果
     */
    public static boolean isRealJson(String json){
        if(json !=null && json.length()>0){
            json = json.trim() ;
            if((json.startsWith("{") || json.startsWith("[")) && (json.endsWith("}") || json.endsWith("]"))){
                return true ;
            }
        }
        return false ;

    }

}
